package org.learn.java.json;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.learn.java.entity.User;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	private static ObjectMapper objectMapper= new ObjectMapper();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		User user = new User();
		user.setId(Long.valueOf(1));
		user.setName("lihua");
		user.setSex("男");
		user.setAge(12);
		String value = tojson(user);

		User u = toObject(value, User.class);
		System.out.println("u:"+u);
	}

	/**
	 * 转JSON
	 * @param object
	 * @return
	 */
	public static String tojson(Object object){
		String result = null;
		try {
			result =  objectMapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("tojson:"+result);
		return result;
	}
	
	/**
	 * 转Object
	 * @param value
	 * @param valueType
	 * @return
	 */
	public static <T> T toObject(String value,Class<T> valueType){
		T result = null;
		try {
			result = objectMapper.readValue(value.getBytes("UTF-8"), valueType);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
}
